<!--
 @description 确认订单-提交订单
 @fileName index.vue
 @author zengqiongying
 @created 2022/08/04 11:23:38
-->
<template>
  <div class="mine-container">
    <MineHeader arrow title="确认订单" bg-color="#F5F6F7" />
    <div class="settle-foot">
      <div class="total-price">应收金额：<span class="price">{{ totalPrice }}</span></div>
      <div class="btn-submit" @click="handleSubmit">提交</div>
    </div>
    <div class="settle-container">
      <div class="s-group">
        <Cell label="门店" :value="formData.saleStoreName" placeholder="点击选择门店" required @right="handleClickStore" />
        <PopPicker
          v-if="showStore"
          v-model="formData.saleStoreCode"
          title="选择门店"
          :show.sync="showStore"
          :lable.sync="formData.saleStoreName"
          :list="storeList"
          value-name="code"
          lable-name="name"
          @selectChange="hanldeStoreChange"
        />
      </div>
      <div class="s-group">
        <Cell
          label="顾客信息"
          :is-column="!!(formData.consumerName)"
          :value="consumerInfo"
          placeholder="点击选择顾客"
          required
          @right="handleClickConsumer"
        />
      </div>
      <div class="s-group">
        <Cell
          label="收货地址"
          :is-column="!!(receiverDTO.consigneeName)"
          :value="receiverInfo"
          placeholder="点击选择收货地址"
          required
          @right="handleClickReceiver"
        >
          <div v-if="!!(receiverDTO.consigneeName)">
            <div class="mt10">{{ receiverInfo }}</div>
            <div>{{ receiverAddrss }}</div>
          </div>
        </Cell>
      </div>
      <div class="s-group">
        <Cell label="家居顾问" :value="homeConsultantName" placeholder="点击选择家居顾问" required @right="handleClickConsultant" />

        <Cell label="销售日期" :value="formData.saleDate" placeholder="点击选择销售日期" required :right="false" @right="handleClickSaleDate" />
        <PopDateTimePicker v-model="showSaleDate" title="销售日期" :default-value="formData.saleDate" :min-date="saleMinDate" :max-date="saleMaxDate" @change="onConfirmSaleDate" />
        <!-- <van-calendar v-model="showSaleDate" color="#05C4C3" title="销售日期" :min-date="saleMaxDate" @confirm="onConfirmSaleDate" /> -->
      </div>
      <div class="s-group">
        <Cell label="配送方式" :value="deliveryModeName" placeholder="点击选择配送方式" required @right="handleClickDeliveryMode" />
        <PopSelect
          v-if="showDeliveryMode"
          v-model="receiverDTO.deliveryMode"
          title="配送方式"
          :list="deliveryModeList"
          value-name="value"
          lable-name="lable"
          :show.sync="showDeliveryMode"
        />

        <Cell label="预计配送日期" :value="receiverDTO.deliveryTime" placeholder="点击选择预约时间" :right="false" required @right="handleClickDeliveryTime" />

        <PopDateTimePicker v-model="showDeliveryTime" title="预计配送日期" :default-value="receiverDTO.deliveryTime" :min-date="minDate" @change="onConfirmDeliveryTime" />
        <!-- <van-calendar v-model="showDeliveryTime" color="#05C4C3" title="预计配送日期" :min-date="minDate" @confirm="onConfirmDeliveryTime" /> -->
      </div>
      <div class="s-group">
        <div class="sku-cell" @click="handleClickSku">
          <div class="sku-list">
            <div v-for="(sku,i) in skuTopList" :key="i" class="list">
              <ImageVideo :src="sku.mainPicUrl" fit="fill" />
            </div>
          </div>
          <div class="icon">
            <van-icon name="weapp-nav" />
          </div>
        </div>
      </div>
      <div class="s-group">
        <Cell label="送装费用" custom :right="false">
          <div class="delivry-fee">
            <van-field
              v-model="formData.deliveryFee"
              format-trigger="onBlur"
              :formatter="formatterPrice"
              class="fee-input"
              type="number"
              label=""
            />
            <div class="unit">元</div>
          </div>
        </Cell>
      </div>
      <div class="s-group">
        <Cell label="商品小计" :right="false" custom>
          <span class="pro-fee">{{ cartTotalFee }}</span>
        </Cell>
        <Cell label="送装费" :value="`+ ￥${formData.deliveryFee}`" :right="false" />
      </div>

      <div class="s-group">
        <Cell label="订单备注" :value="formData.remark" placeholder="请输入订单备注" @right="handleClickRemark" />
        <PopField
          v-if="showRemark"
          v-model="formData.remark"
          title="订单备注"
          :show.sync="showRemark"
        />
      </div>

    </div>

    <PopSkuList if="showAllSku" :show.sync="showAllSku" :list="skuList" />

    <Popup
      v-if="submitPop.show"
      v-model="submitPop.show"
      msg-align="center"
      :icon="submitPop.icon"
      :closeable="false"
      :show-cancel-button="submitPop.showCancel"
      :cancel-button-text="submitPop.cancelText"
      :confirm-button-text="submitPop.confirmText"
      @confirm="handlePopConfirm"
      @cancel="handlePopCancel"
    >
      <div class="submit-pop-content">
        <div>{{ submitPop.message }}</div>
        <div v-if="submitPop.warningMsg" class="warning-txt">
          {{ submitPop.warningMsg }}
        </div>
      </div>
    </Popup>
  </div>
</template>

<script>
import MineHeader from '@/components/MineHeader'
import Cell from './components/Cell'
import ImageVideo from '@/components/ImageVideo'
import Popup from '@/components/Popup'
import PopSelect from '@/components/PopSelect'
import PopField from '@/components/PopField'
import PopPicker from '@/components/PopPicker'
import PopDateTimePicker from '@/components/PopDateTimePicker'
import PopSkuList from './components/SkuList'
import { parseTime } from '@/utils'
import { queryBatchList } from '@/apis/cart'
import { commitOrder, queryStore, queryCurrentShoppingGuide } from '@/apis/order'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'OrderCommit',
  components: {
    MineHeader, Cell, ImageVideo,
    Popup,
    PopSelect,
    PopField,
    PopPicker,
    PopDateTimePicker,
    PopSkuList
  },
  data() {
    return {
      cartIds: this.$route.query.ids || '',
      formData: {
        sadOrderCode: this.$route.query.settleCode || '', // 结算订单码
        // disCode: '', // 经销商编码
        // disName: '', // 经销商名称
        // mdmOrgCode: '', // mdm门店编码-必传-新增顾客使用 （后端去查询）
        // qyConsumerCode: '', // 消费者编码-消费者中心

        saleStoreCode: '', // 门店
        saleStoreName: '',
        consumerName: '', // 顾客姓名-门店
        consumerPhone: '', // 顾客联系电话-门店
        consumerPhoneBak: '', // 顾客备用联系电话-门店

        saleDate: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'), // 销售日期
        deliveryFee: '0', // 送装费用
        remark: '' // 订单备注(非必填)
      },
      receiverDTO: {
        consigneeName: '', // 收货人姓名
        consigneePhone: '', // 收货人电话
        consigneePhoneBak: '', // 收货人备用电话 (非必填)
        receiverProvinceId: '',
        receiverProvince: '',
        receiverProvinceCode: '',
        receiverCityId: '',
        receiverCity: '',
        receiverCityCode: '',
        receiverDistrictId: '',
        receiverDistrict: '',
        receiverDistrictCode: '',
        receiverTownId: '',
        receiverTown: '',
        receiverTownCode: '',
        receiverAddress: '',

        deliveryTime: '', // 预计配送日期
        deliveryMode: '02', // 配送方式：01自提02送装-必填
        deliveryFee: '' // 配送费用(非必填)
      }, // 收货信息
      homeConsultantList: [
        // {homeConsultantCode,homeConsultantName,homeConsultantPhone}
      ], // 家居顾问
      skuList: [],
      storeList: [], // 门店列表
      deliveryModeList: [
        { lable: '配送', value: '02' },
        { lable: '自提', value: '01' }
      ],

      showStore: false,
      showSaleDate: false,
      saleMinDate: '', // 销售日期可选择的最小日期
      saleMaxDate: '', // 销售日期可选择的最大日期
      minDate: '', // 预计送货日期选择最小日期
      showDeliveryTime: false,
      showDeliveryMode: false,
      showAllSku: false,
      showRemark: false,
      orderId: '',
      submitPop: {
        type: '', // 成功pop提示：succes , 失败pop提示：error
        message: '',
        show: false,
        closeable: false,
        icon: 'success',
        cancelText: '取消',
        confirmText: '确定',
        warningMsg: ''
      } // 提交订单后提示信息
    }
  },

  computed: {
    ...mapGetters('order', ['consumer', 'receiver', 'consultant']),
    skuTopList() {
      const res = this.skuList.slice(0, 4)
      return res
    },
    // 顾客信息
    consumerInfo() {
      const { consumerName, consumerPhone, consumerPhoneBak } = this.formData
      const tmp = []
      if (consumerName) {
        tmp.push(consumerName)
      }
      if (consumerPhone) {
        tmp.push(consumerPhone)
      }
      if (consumerPhoneBak) {
        tmp.push(consumerPhoneBak)
      }
      return tmp.join(', ')
    },
    // 收货人
    receiverInfo() {
      const { consigneeName, consigneePhone, consigneePhoneBak } = this.receiverDTO
      const tmp = []
      if (consigneeName) {
        tmp.push(consigneeName)
      }
      if (consigneePhone) {
        tmp.push(consigneePhone)
      }
      if (consigneePhoneBak) {
        tmp.push(consigneePhoneBak)
      }
      return tmp.join(', ')
    },
    // 收货地址
    receiverAddrss() {
      const { receiverProvince = '', receiverCity = '', receiverDistrict = '', receiverTown = '', receiverAddress = '' } = this.receiverDTO
      const tmp = [receiverProvince, receiverCity, receiverDistrict, receiverTown, receiverAddress]
      return tmp.join('')
    },
    // 家居顾问
    homeConsultantName() {
      return this.homeConsultantList.map(v => {
        return v.homeConsultantName
      }).join(',')
    },
    deliveryModeName() {
      return this.receiverDTO.deliveryMode === '01' ? '自提' : this.receiverDTO.deliveryMode === '02' ? '配送' : ''
    },
    // 商品费用小计
    cartTotalFee() {
      let fee = 0
      this.skuList.forEach(v => {
        let price = Number(v.salePrice || 0)
        if (price > 0 && (v.productFlag === '03' || v.productFlag === '05')) {
          price = 0
        }
        fee += price * Number(v.quantity || 0)
      })
      return Math.floor(fee * 100) / 100
    },
    // 应收金额
    totalPrice() {
      const price = this.cartTotalFee + Number(this.formData.deliveryFee || 0)
      return Number(price).toFixed('2')
    }

  },
  watch: {
    consumer: {
      handler(val) {
        this.updateFormConsumer(val)
      },
      deep: true
    },
    receiver: {
      handler(val) {
        this.updateFormReceiver(val)
      },
      deep: true
    },
    consultant: {
      handler(val) {
        this.updateHomeConsultant(val)
      },
      deep: true
    }
  },
  created() {
    this.getSkuList()
    const date = new Date()
    const sDate = new Date().setMonth(date.getMonth() - 6)
    this.saleMinDate = new Date(sDate)
    this.saleMaxDate = date
    this.minDate = date // parseTime(date, '{y}-{m}-{d}')
    this.getStoreList()
    this.getUserConsulat()
  },
  activated() {
    this.updateFormConsumer(this.consumer)
    this.updateFormReceiver(this.receiver)
  },

  mounted() {},
  beforeRouteLeave(to, from, next) {
    const paths = ['/editConsumer', '/editRecever', '/editConsultant']
    if (!paths.includes(to.path)) {
      this.$removeKeepAliveCache(this)
    }
    next()
  },

  methods: {
    ...mapMutations('order', ['updateConsumer', 'updateReceiver', 'updateConsultant']),
    // 查询当前用户的家居顾问岗位
    getUserConsulat() {
      queryCurrentShoppingGuide().then(res => {
        const records = (res.data && res.data.records) || []
        if (records.length > 0) {
          const { code, name, phone } = records[0]
          this.updateConsultant([{ code, name, phone }])
        }
      })
    },
    // 查询商品
    getSkuList() {
      const ids = this.cartIds.split(',')
      queryBatchList(ids).then(res => {
        this.skuList = res.data || []
      })
    },
    // 获取门店信息
    getStoreList() {
      queryStore().then(res => {
        const list = res.data || []
        if (list.length === 1) {
          const tmp = list[0]
          // const { mdmOrgCode, mdmOrgName, code, name } = tmp
          const { code, name } = tmp
          this.formData.saleStoreCode = code
          this.formData.saleStoreName = name
          // this.formData.mdmOrgCode = mdmOrgCode
          if (!this.receiver || !this.receiver.consigneeName || this.receiver.consigneeName === '') {
            this.updateReceiverFromStore(tmp)
          }
        }
        this.storeList = list
      })
    },
    // 格式化销售价格
    formatterPrice(value) {
      const val = Math.floor(value * 100) / 100
      if (val < 0) {
        this.$toast('输入送装费用不能小于0')
        return '0'
      }
      return val
    },
    // 更新顾客信息
    updateFormConsumer(data) {
      this.$set(this.formData, 'consumerName', data && data.consumerName || '')
      this.$set(this.formData, 'consumerPhone', data && data.consumerPhone || '')
      this.$set(this.formData, 'consumerPhoneBak', data && data.consumerPhoneBak || '')
    },
    // 更新收货信息
    updateFormReceiver(data) {
      const exKey = ['deliveryTime', 'deliveryMode', 'deliveryFee']
      for (const key in this.receiverDTO) {
        if (!exKey.includes(key)) {
          this.$set(this.receiverDTO, key, data && data[key] || '')
        }
      }
    },
    // 根据店铺数据更新收货地区
    updateReceiverFromStore(data) {
      const params = this.receiver && this.receiver.consigneeName ? this.receiver : {}
      const newVal = { ...params, ...{
        receiverProvince: data.provinceName || '',
        receiverProvinceCode: data.provinceCode || '',
        receiverProvinceId: '', // data.province || '',
        receiverCity: data.cityName || '',
        receiverCityCode: data.cityCode || '',
        receiverCityId: '', // data.city || '',
        receiverDistrict: data.countyName || '',
        receiverDistrictCode: data.countyCode || '',
        receiverDistrictId: '', // data.county || '',
        receiverTown: data.townName || '',
        receiverTownCode: data.townCode || '',
        receiverTownId: '' // data.town ||
      }}
      this.updateReceiver(newVal)
    },
    // 更新家居顾问信息
    updateHomeConsultant(data) {
      let list = []
      if (data && data.length) {
        list = data.map(v => {
          return {
            homeConsultantCode: v.code,
            homeConsultantName: v.name,
            homeConsultantPhone: v.phone
          }
        })
      }
      this.homeConsultantList = list
    },
    handleClickStore() {
      this.showStore = true
    },
    hanldeStoreChange(data) {
      // const mdmOrgCode = (data && data.mdmOrgCode) || ''
      // this.formData.mdmOrgCode = mdmOrgCode
      if (!this.receiver || !this.receiver.consigneeName || this.receiver.consigneeName === '') {
        this.updateReceiverFromStore(data)
      }
    },
    handleClickConsumer() {
      this.$router.push({ path: '/editConsumer' })
    },
    handleClickReceiver() {
      this.$router.push({ path: '/editRecever' })
    },

    handleClickConsultant() {
      if (!this.formData.saleStoreCode) {
        this.$toast('请先选择门店后再选择家居顾问')
        return
      }
      this.$router.push({ path: '/editConsultant', query: { shopCode: this.formData.saleStoreCode }})
    },
    handleClickSaleDate() {
      this.showSaleDate = true
    },
    onConfirmSaleDate(date) {
      this.formData.saleDate = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
      this.showSaleDate = false
    },
    handleClickDeliveryTime() {
      this.showDeliveryTime = true
    },
    onConfirmDeliveryTime(date) {
      this.receiverDTO.deliveryTime = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
      this.showDeliveryTime = false
    },
    handleClickDeliveryMode() {
      this.showDeliveryMode = true
    },
    handleClickSku() {
      this.showAllSku = true
    },
    handleClickRemark() {
      this.showRemark = true
    },
    getParams() {
      const { saleStoreCode, consumerName, saleDate, deliveryFee } = this.formData
      if (!this.$isDef(saleStoreCode) || this.$isEmpty(saleStoreCode)) {
        this.$toast('门店信息不能为空')
        return false
      }
      if (!this.$isDef(consumerName) || this.$isEmpty(consumerName)) {
        this.$toast('顾客信息不能为空')
        return false
      }
      if (!this.$isDef(consumerName) || this.$isEmpty(consumerName)) {
        this.$toast('顾客信息不能为空')
        return false
      }
      const { consigneeName, deliveryTime, deliveryMode } = this.receiverDTO
      if (!this.$isDef(consigneeName) || this.$isEmpty(consigneeName)) {
        this.$toast('收货信息不能为空')
        return false
      }
      if (!this.homeConsultantList.length === 0) {
        this.$toast('家居顾问不能为空')
        return false
      }
      if (!this.$isDef(saleDate) || this.$isEmpty(saleDate)) {
        this.$toast('零售日期不能为空')
        return false
      }
      if (!this.$isDef(deliveryMode) || this.$isEmpty(deliveryMode)) {
        this.$toast('配送方式不能为空')
        return false
      }
      if (!this.$isDef(deliveryTime) || this.$isEmpty(deliveryTime)) {
        this.$toast('预计配送日期不能为空')
        return false
      }
      if (!this.$isDef(deliveryFee) || this.$isEmpty(deliveryFee)) {
        this.$toast('送装费不能为空')
        return false
      }
      const homeConsultantList = this.homeConsultantList.map(v => {
        return v
      })
      const skuList = this.skuList.map(v => {
        const flag = ['03', '05'].includes(v.productFlag)
        let salePrice = v.salePrice || 0
        if (flag) {
          // 赠品单价必须为0
          salePrice = 0
        }
        if (v.isActivity === 1 && Number(v.orangePrice || 0) < Number(v.salePrice || 0)) {
          // 特价商品(活动商品)单价不能大于原价
          salePrice = v.orangePrice
        }
        return { ...v, ...{ salePrice }}
      })
      return {
        ...this.formData,
        ...{
          receiverDTO: this.receiverDTO,
          homeConsultantList,
          skuList
        }
      }
    },
    handleSubmit() {
      const params = this.getParams()
      if (!params) {
        return false
      }
      commitOrder(params).then(res => {
        if (res.success === 1) {
          this.orderId = res.msg
          this.submitPop = {
            type: 'success',
            show: true,
            closeable: false,
            icon: 'success',
            showCancel: true,
            cancelText: '不收款',
            confirmText: '去收款',
            message: '提交成功，是否进行收款？',
            warningMsg: '注意：若暂时不进行收款，后续可在电脑端进行收款'
          }
        }
      }).catch((msg) => {
        this.submitPop = {
          type: 'error',
          show: true,
          closeable: true,
          icon: 'error',
          showCancel: false,
          cancelText: '取消',
          confirmText: '确定',
          message: msg || '订单提交失败，请稍后重试！',
          warningMsg: false
        }
      })
    },
    handlePopConfirm() {
      if (this.submitPop.type === 'success') {
        this.clearCacheData()
        this.$router.replace({
          path: '/my/order/settle/' + this.orderId
          /* query: {
            fee: this.totalPrice
          } */
        })
      } else {
        this.submitPop.show = false
      }
    },
    handlePopCancel() {
      this.clearCacheData()
      this.$router.replace({
        path: '/my/order'
      })
    },
    clearCacheData() {
      this.updateConsultant(null)
      this.updateConsumer(null)
      this.updateReceiver(null)
    }
  }
}

</script>
<style lang='less' scoped>
  .settle-foot{
    position: fixed;
    z-index: 99;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12PX 16PX 22PX;
    height: 74PX;
    border-top:1px solid rgba(60, 68, 88, 0.1);
    box-sizing: border-box;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .total-price{
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 12PX;
      .price{
        display: flex;
        align-items: center;
        font-size: 20PX;
        font-weight: 500;
        color: #EA5B31;
        line-height: 28PX;
        &::before{
          content: '¥';
          font-size: 12PX;
          margin-right: 4px;
        }
      }
    }
    .btn-submit{
      margin-left:10px;
      width: 130px;
      height: 40PX;
      background: linear-gradient(180deg, #F6945F 0%, #EA5B31 100%);
      border-radius: 21PX;
      color: #FFFFFF;
      font-weight: bold;
      font-size: 14PX;
      line-height: 40PX;
      text-align: center;
      letter-spacing: 1px;
    }
  }
  .settle-container{
    padding: 16px 16px 74PX;
    .mt10{
      margin-bottom: 10px;
    }
    .s-group{
      margin-bottom: 10px;
      padding: 10px 12px;
      background: #FFFFFF;
      border-radius: 12px;
    }
    .delivry-fee{
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .fee-input{
        padding: 0;
        width: 60px;
        height: 26px;
        line-height: 26px;
        text-align: center;
        box-sizing: border-box;
        background: rgba(229, 230, 233, 0.5);
        border-radius: 2px;
        /deep/.van-field__control{
          text-align: center;
          color: #111111;
          font-weight: bold;
          font-size: 14px;
        }
      }
      .unit{
        font-size: 14px;
        color:#999999 ;
        margin-left: 4px;
      }
    }
    .pro-fee{
      color:#FF634C;
      font-size:18px;
      &::before{
        content: '￥';
        font-size: 14px;
      }
    }
  }
  .sku-cell{
    display: flex;
    align-items: center;
    .sku-list{
      display: flex;
      align-items: center;
      flex: 1;
      --width: calc(100% - 30px);
      .list{
        // width:calc(var(--width)/4);
        // height:calc(var(--width)/4);
        width: 58px;
        height: 58px;
        margin-right: 10px;
        border-radius: 6px;
        overflow: hidden;
        background: rgba(125,128,145,0.2);
        &:last-child{
          margin-right: 0;
        }
      }
    }
    .icon{
      width: 40px;
      text-align: center;
      color: rgba(125, 128, 145, 0.5);
      font-size: 20px;
    }
  }
  .submit-pop-content{
    padding-bottom: 15px;
    line-height: 24px;
    font-size: 18px;
    text-align: center;
    color: #343640;
    font-weight: bold;
    .warning-txt{
      margin-top: 17px;
      font-size: 12px;
      font-weight: normal;
      color: #FF634C;
      line-height: 20px;
    }
  }
</style>
